package watcher

import (
	"io"
	"fmt"
	"os/exec"
	"os"
	"github.com/gliderlabs/ssh"
	"github.com/kr/pty"
	"../utils"
)

func (pws *ProcWatcherService) handle(session ssh.Session)  {
	input := session.Command()
	//addr := utils.chop(session.RemoteAddr().String())
	//user := session.User()
	if len(input)<2{
		io.WriteString(session, "command should be [procname command]\n")
	}
	pname:=input[0]
	cname:=input[1]
	pws.mu.RLock()
	defer pws.mu.RUnlock()
	p,ok:=pws.procs[pname]
	if !ok{
		io.WriteString(session, fmt.Sprintf("proc %s not defined\n",pname))
	}
	c,ok:=p.Commands[cname]
	if !ok{
		io.WriteString(session, fmt.Sprintf("command %s not defined\n",cname))
	}
	ptyReq, winCh, isPty := session.Pty()
	if !isPty {
		io.WriteString(session, fmt.Sprintf("No PTY requested\n try to use:\n ssh -tt xx.xx.xx.xx command"))
	}
	cmd:=exec.Command(c[0],c[1:]...)
	var err error
	if cmd.Dir, err = os.Getwd(); err != nil {
		io.WriteString(session, fmt.Sprintf("get pwd error %v \n",err))
	}
	cmd.Env = append(cmd.Env, os.Environ()...)
	cmd.Env = append(cmd.Env, fmt.Sprintf("TERM=%s", ptyReq.Term))
	f, err := pty.Start(cmd)
	if err != nil {
		io.WriteString(session,  fmt.Sprintf("command error: %v", err))
	}
	go func() { //调整窗口大小
		for win := range winCh {
			utils.SetWinsize(f, win.Width, win.Height)
		}
	}()
	go func() { //读输入
		io.Copy(f, session) // stdin
	}()
	io.Copy(session, f)
}

